package com.xgc.book.bookserver.util.tencent;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.xgc.book.bookserver.util.exception.RTException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author PangJunjie
 * @Date 2023/11/28/028
 */
@Component
public class SmsUtil {
    @Value("${tx.sms.SecretId}")
    private String SecretId;
    @Value("${tx.sms.SecretKey}")
    private String SecretKey;
    @Value("${tx.sms.SDKAppID}")
    private String SDKAppID;
    @Value("${tx.sms.SignName}")
    private String SignName;
    @Value("${tx.sms.loginTemp}")
    private String loginTemp;

    public String sendMsm(String phone, String code) {

        // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        Credential cred = new Credential(SecretId, SecretKey);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        SendSmsRequest req = new SendSmsRequest();
        String[] phoneNumberSet1 = {"+86" + phone};
        req.setPhoneNumberSet(phoneNumberSet1);
        req.setSmsSdkAppid(SDKAppID);
        req.setSign(SignName);
        req.setTemplateID(loginTemp);

        String[] templateParamSet1 = {code};
        req.setTemplateParamSet(templateParamSet1);
        // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
        SendSmsResponse resp = null;
        try {
            resp = client.SendSms(req);
        } catch (TencentCloudSDKException e) {
            throw new RTException(e.getMessage());
        }
        // 输出json格式的字符串回包
        return SendSmsResponse.toJsonString(resp);
    }
}
